package com.lam.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class PinyinUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(PinyinUtil.class);

	/**
     * 将汉字转换为全拼
     *
     * @param text 文本
     * @param separator 分隔符
     * @return {@link String}
     */
    public static String convert2Py(String text) {
    	return convert2Py(text, StringUtils.EMPTY);
    }
    /**
     * 将汉字转换为全拼
     *
     * @param text 文本
     * @param separator 分隔符
     * @return {@link String}
     */
    public static String convert2Py(String text, String separator) {
        
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        // 设置大小写
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 设置声调表示方法
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        // 设置字母u表示方法
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        try {
            StringBuilder sb = new StringBuilder();
            char[] chars = text.toCharArray();
            String[] s;
            for (int i = 0; i < chars.length; i++) {
                // 判断是否为汉字字符
                if (String.valueOf(chars[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    s = PinyinHelper.toHanyuPinyinStringArray(chars[i], format);
                    if (s != null) {
                        sb.append(s[0]).append(separator);
                        continue;
                    }
                }
                sb.append(String.valueOf(chars[i])).append(separator);
            }
            return sb.substring(0, sb.length() - 1);
        } catch (Exception e) {
            logger.error("转换拼音异常", e);
            return StringUtils.EMPTY;
        }
        
    }

    /**
     * 获取汉字首字母
     *
     * @param text 文本
     * @return {@link String}
     */
    public static String getPinyinInitials(String text) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            String[] s = PinyinHelper.toHanyuPinyinStringArray(ch);
            if (s != null) {
                sb.append(s[0].charAt(0));
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}
